﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace Intex.Controls.Stopwatch.Controllers
{
    public class XM058BController : IStopwatchController
    {
        private string recivedStr = string.Empty;
        private string oldStr = string.Empty;

        public StopwatchValue ReadData(SerialPort serialPort)
        {
            Thread.Sleep(100);
            try
            {
                int iLen;
                iLen = serialPort.BytesToRead;

                Byte[] chrdata = new Byte[iLen];
                serialPort.Read(chrdata, 0, iLen);
                for (int i = 0; i < iLen; i++)
                {
                    recivedStr += (chrdata[i].ToString("X2") == "55" ? Environment.NewLine : string.Empty) + chrdata[i].ToString("X2") + " ";
                    if (recivedStr.Length > 100)
                        break;
                }
                //取最后一次的有效值.
                Regex paramReg = new Regex(@"(?<p>55.+)");
                MatchCollection matches = paramReg.Matches(String.Concat(recivedStr, " "));
                if (matches.Count > 0)
                {
                    recivedStr = string.Empty;
                    serialPort.DiscardOutBuffer();
                    Match m = matches[matches.Count - 1];
                    oldStr = m.Groups["p"].Value;
                }

                //oldStr = "55 aa 20 0c 12 00 07 cd 00 00 01 12";
                var data = oldStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (data.Length != 12)
                    return new StopwatchValue();

                var statusCode = Convert.ToInt32(data[4], 16);
                //小数位数
                var digitCode = (statusCode & 3);
                decimal digits = 0m;
                if (digitCode == 1)
                {
                    digits = 0.1m;
                }
                else if (digitCode == 2)
                {
                    digits = 0.01m;
                }
                //单位
                var unitCode = statusCode & 0x10;
                var unit = "米";
                if (unitCode == 0x10)
                {
                    unit = "码";
                }

                //长度
                Int64 ilength = Convert.ToInt64(string.Concat(data[5], data[6], data[7]), 16);
                var nLength = ilength * digits;

                return new StopwatchValue() { Length = nLength, Speed = 0, Unit = unit };
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public int chartohex(char chr1, char chr2)
        {
            int cTemp1, cTemp2;
            if (chr1 > '9' && chr1 <= 'F')
                cTemp1 = chr1 - 'A' + 10;
            else if (chr1 >= '0' && chr1 <= '9')
                cTemp1 = chr1 - '0';
            else
                cTemp1 = 0;

            if (chr2 > '9' && chr2 <= 'F')
                cTemp2 = chr2 - 'A' + 10;
            else if (chr2 >= '0' && chr2 <= '9')
                cTemp2 = chr2 - '0';
            else
                cTemp2 = 0;
            cTemp2 += cTemp1 * 0x10;
            return cTemp2;
        }

        public void SendCommand(SerialPort serialPort)
        {
            if (serialPort.IsOpen)
            {
                var cmd = "55AA02000001";

                Byte[] chrdata = new Byte[100];
                cmd = cmd.ToUpper();
                cmd = cmd.Replace(" ", "");
                var iLen = cmd.Length;
                iLen = iLen / 2;
                int i = 0;
                for (i = 0; i < iLen; i++)
                {
                    chrdata[i] = (Byte)chartohex(cmd[2 * i], cmd[2 * i + 1]);
                }

                serialPort.DiscardOutBuffer();
                serialPort.DiscardInBuffer();
                serialPort.Write(chrdata, 0, i);
            }
        }
    }
}
